import os
import sys
import subprocess
import shutil
import urllib.parse


def convert_docx_to_wiki(docx_path):
    # 获取文件名和文件扩展名
    file_name, file_ext = os.path.splitext(os.path.basename(docx_path))

    # 创建输出目录
    output_dir = os.path.join("converted", file_name)
    # 如果存在目录，则删除，然后创建目录
    if os.path.exists(output_dir):
        shutil.rmtree(output_dir)

    os.makedirs(output_dir, exist_ok=True)

    # 转换docx到markdown
    markdown_path = os.path.join(output_dir, file_name + ".md")
    subprocess.run(
        [
            "pandoc",
            "-t",
            "markdown",
            "-o",
            markdown_path,
            "--extract-media=" + output_dir,
            docx_path,
        ]
    )

    # 转换markdown到mediawiki
    wiki_path = os.path.join(output_dir, file_name + ".wiki")
    subprocess.run(
        ["pandoc", markdown_path, "-f", "markdown", "-t", "mediawiki", "-o", wiki_path]
    )

    media_dir = f"{output_dir}/media"
    # 修改图片文件名
    print("修改图片文件名")
    image_files = os.listdir(media_dir)
    image_len = len(image_files)
    for i, file in enumerate(image_files):
        end_str = "\r"
        if i == image_len - 1:
            end_str = "\n"

        print(f"修改图片文件名: {i+1}/{image_len}", end=end_str)
        old_file_path = os.path.join(media_dir, file)
        new_file_path = os.path.join(media_dir, file_name + "_" + file)
        os.rename(old_file_path, new_file_path)

    # 替换.wiki文件中的图片路径
    old_uri = urllib.parse.quote(f"{output_dir}/media/", safe="\\/")
    print(f"替换 {old_uri} --> {file_name}_")
    with open(wiki_path, "r", encoding="utf-8") as f:
        wiki_content = f.read()
        wiki_content = wiki_content.replace(old_uri, f"{file_name}_")
        with open(wiki_path, "w", encoding="utf-8") as f:
            f.write(wiki_content)

    print(f"转换成功 {docx_path} to {wiki_path}")


if __name__ == "__main__":
    # 获取传参 argvs
    docx_path = sys.argv[1]

    if not docx_path:
        print("请传入文件路径")
        sys.exit(1)

    if not os.path.isfile(docx_path):
        print("文件不存在")
        sys.exit(1)

    convert_docx_to_wiki(docx_path)
